
var app = getApp();
var api = require('../../utils/util.js');
var util = require('../../utils/util.js');
var addressList = null;
Page({
  data: {
    freight:0,//运费
    parameter:"请选择参数",
    provinceIndex: 0, //省份
    cityIndex: 0, //城市
    countyIndex: 0, //区县
    producData:null,
    isLike: true,
    num: 1,//初始数量
    amount: 0,//初始金额
    minusStatus: 'disabled',
    // 使用data数据对象设置样式名
    choose_modal: "none",
    choo_modal: "none",
    choose1_modal: "none",
    choose2_modal: "none",
    choose3_modal: "none",
    choo_modal_activity: "none",
    // 规格数量框
    flag: 0,//点选规格时来源 0：规格点 1：立即购买 2：加入购物车
    pAndNList:[],
    count:0,
    selectName: "",//已选的属性名字
    selectAttrid: [],//选择的属性id
    //商品信息
    goods_info: {},
    // banner
    imgUrls: [
  
    ],
    point:0,
    indicatorDots: true, //是否显示面板指示点
    autoplay: true, //是否自动切换
    duration: 1000, //  滑动动画时长1s
    interval: 2000,
    quest_modal: "none",
    // 商品详情介绍
    deschtml:"",
    index:0,
    buyMethod:1,
    shoucang:false,
    video: "",//视频
    coverUrl: "",//视频封面图
    specIdList:[],
    specNameList:[],
    twoChoose:false,
    share_modal: 'none',
    choo_friends: 'none',
    choo_modal_li:'none',
    modalName1: '',
  },
  onLoad: function (options) {
    var that = this;
    console.info(options);
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
        } else {
          this.choo_modal_li_s();
        }
      }
    })
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight,
      type: options.type,
      discount: options.discount,
      time: util.formatTime(new Date()),
      yushou: options.yushou,
      lipinka: options.lipinka,
      typeName1: options.typeName1,
      communityGroup: options.communityGroup,
      communityheadid: options.communityheadid,
      nickname: options.nickname,
      community: options.community,
      level:wx.getStorageSync("level"),
    })
    if (options.partnerUserId == undefined) {
      that.setData({
        partnerUserId: 0 
      })
    } else {
      that.setData({
        partnerUserId: options.partnerUserId
      })
    }
    console.info('aaaa' + options.type);
    let endTimeList = [];
    that.setData({
      productid:options.productid,
      back: options.back
    })
    var productid = options.productid
    if (!options.scene) {

    } else {

      var getQueryString = {}
      var strs = decodeURIComponent(options.scene).split('&') //以&分割
      for (var i = 0; i < strs.length; i++) {
        getQueryString[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
      }
      console.info(getQueryString['pt']);
      productid = getQueryString['productid'] || ''
      this.setData({
        type: getQueryString['type'] || '',
        productId: getQueryString['productid'] || '',
        back :1
      })
    }
    if (that.data.type == 2) {
      //拼团商品
      console.info("拼团商品");
      wx.request({
        url: app.globalData.url + "getProductDetailByProductId",
        data: {
          productId: options.productid,
          userId:wx.getStorageSync("userId")
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.info(res.data);
          var data = res.data.data;
          var questionProducts = res.data.questionProducts;
          var imgs = [];
          var pcount = data.product.inventoryQuantity;
          that.setData({
            producData: data.product,
            deschtml: data.detail,
            imgUrls: imgs,
            count: pcount,
            productId: data.product.productId,
            productTypeId: data.product.productTypeId,
            listProduct: questionProducts,
            price: data.product.groupShoppingPrice,
            price1: data.product.groupShoppingPrice,
            point: data.product.minPoint,
            minPrice: data.product.minPrice,
            thumbnailImage: data.product.thumbnailImage,
            rebatePrice: data.product.rebatePrice,
            memberPrice: data.product.memberPrice,
          })
          if(data.productSpec!=undefined){
            that.setData({
              productSpec:JSON.parse(data.productSpec)
            })
          }
          wx.request({
            url: app.globalData.url + "getCouponListBy",
            data: {
              productId: data.product.productId,
              productTypeId: data.product.productTypeId,
              userId: wx.getStorageSync("userId"),
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              that.setData({
                cpdata: res.data.data
              })
              if (res.data.data.length >= 1) {
                
                that.setData({
                  cpdatathreshold: res.data.data[0].threshold,
                  cpdataprice: res.data.data[0].price
                })
              }
              if (res.data.data.length >= 2) {
                console.info(111);
                that.setData({
                  cpdatathreshold1: res.data.data[1].threshold,
                  cpdataprice1: res.data.data[1].price,
                })
              }

            },
          })
        },
      })
      this.getAddress(productid);
      wx.request({
        url: app.globalData.url + 'getProductEvaluation',
        data: { productId: productid },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: function (res) {
          that.setData({
            evaluationList: res.data.data.reverse(),
          });
          for (var i = 0; i < that.data.evaluationList.length;i++){
            that.data.evaluationList[i].reviewContent = that.entitiesToUtf16(that.data.evaluationList[i].reviewContent)
          }
          that.setData({
            evaluationList: that.data.evaluationList
          });
          var imgArr = [];
          for (var i = 0; i < res.data.data.length; i++) {
            var evaImg = res.data.data[i].reviewImages;
            var arr1 = evaImg.split(';;;');
            if (arr1[arr1.length - 1].trim() == "") {
              arr1.length = arr1.length - 1;
            }
            imgArr.push(arr1);
          }
          that.setData({
            imageList: imgArr,
          });
        }
      });
      //参加带拼团的
      wx.request({
        url: app.globalData.url + 'getWaitJoinGroupShopping',
        data: { },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: function (res) {
          that.setData({
            waitJoinGroup: res.data.data,
          });
        }
      })
      wx.request({
        url: app.globalData.url + "getGroupShoppingListByProductId",
        data: {
          productId: productid,
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          if (res.data.result == 1) {
            var endTimeList = new Array();
            for(var i=0;i<res.data.data.length;i++){
              endTimeList[i] = res.data.data[i].endTime;
            }
            that.getTimeList(endTimeList)
            that.setData({
              gropuShopList: res.data.data,
            })
            that.interval();
          } else {
            that.setData({
              gropuShopList: 0
            })
          }
        },
      })
     
    } 
    if (that.data.type != 2)  {
      //秒杀和普通
      wx.request({
        url: app.globalData.url + "getProductDetailByProductId",
        data: {
          productId: productid,
          userId: wx.getStorageSync("userId")
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var data = res.data.data;
          var questionProducts = res.data.questionProducts;
          var imgs = [];
          var pcount = data.product.inventoryQuantity;
          console.info(data);
          if (data.product.bookingConsignmentTime != undefined && data.product.bookingEndTime != undefined) {
            data.product.bookingConsignmentTime = data.product.bookingConsignmentTime.substring(0, 10); //要截取时间的字符串
            data.product.bookingEndTime = data.product.bookingEndTime.substring(0, 10); //要截取时间的字符串
          }
          if (data.product.seckillEndTime != undefined) {
            //秒杀
            console.log(data.product)
            that.setData({
              producData: data.product,
              deschtml: data.detail,
              imgUrls: imgs,
              count: pcount,
              originalPrice: data.product.originalPrice,
              price: data.product.price,
              price1: data.product.price,
              point: data.product.minPoint,
              thumbnailImage: data.product.thumbnailImage,
              seckillEndTime: data.product.seckillEndTime,
              seckillNum: data.product.seckillLimitNum,
              productId: data.product.productId,
              productTypeId: data.product.productTypeId,
              listProduct: questionProducts,
              minPrice: data.product.minPrice,
              activity: data.product.promotionMsgList,
              groupShoppingLimitNum: data.product.groupShoppingLimitNum,
              rebatePrice: data.product.rebatePrice,
              memberPrice: data.product.memberPrice,
            })
            that.countTime(that.data.seckillEndTime)
          } else {
            that.setData({
              producData: data.product,
              deschtml: data.detail,
              imgUrls: imgs,
              count: pcount,
              originalPrice: data.product.originalPrice,
              price: data.product.price,
              price1: data.product.price,
              point: data.product.minPoint,
              thumbnailImage: data.product.thumbnailImage,
              seckillEndTime: data.product.seckillEndTime,
              seckillNum: data.product.seckillLimitNum,
              productId: data.product.productId,
              productTypeId: data.product.productTypeId,
              listProduct: questionProducts,
              minPrice: data.product.minPrice,
              bookingEndTime: data.product.bookingEndTime,
              bookingConsignmentTime: data.product.bookingConsignmentTime,
              activity: data.product.promotionMsgList,
              groupShoppingLimitNum: data.product.groupShoppingLimitNum,
              rebatePrice: data.product.rebatePrice,
              memberPrice: data.product.memberPrice,
            })
            if(data.productSpec!=undefined){
              that.setData({
                productSpec:JSON.parse(data.productSpec)
              })
            }
           
          }
          that.setData({
            gropuShopList:0,
          })
          console.info(88888);
          wx.request({
            url: app.globalData.url + "getCouponListBy",
            data: {
              productId: data.product.productId,
              productTypeId: data.product.productTypeId,
              userId:wx.getStorageSync("userId"),
              category:0
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              that.setData({
                cpdata: res.data.data
              })
              if (res.data.data.length >=1) {
                that.setData({
                  cpdatathreshold: res.data.data[0].threshold,
                  cpdataprice: res.data.data[0].price
                })
              }
              if (res.data.data.length >= 2) {
                that.setData({
                  cpdatathreshold1: res.data.data[1].threshold,
                  cpdataprice1: res.data.data[1].price,
                })
              }
              
            },
          })
        },
      })
      this.getAddress(productid);
      wx.request({
        url: app.globalData.url + 'getProductEvaluation',
        data: { productId: productid },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: function (res) {
          that.setData({
            evaluationList: res.data.data.reverse(),
          });
          for (var i = 0; i < that.data.evaluationList.length; i++) {
            that.data.evaluationList[i].reviewContent = that.entitiesToUtf16(that.data.evaluationList[i].reviewContent)
          }
          that.setData({
            evaluationList: that.data.evaluationList
          });
          var imgArr = [];
          for (var i = 0; i < res.data.data.length; i++) {
            var evaImg = res.data.data[i].reviewImages;
            var arr1 = evaImg.split(';;;');
            if (arr1[arr1.length - 1].trim() == "") {
              arr1.length = arr1.length - 1;
            }
            imgArr.push(arr1);
          }
          that.setData({
            imageList: imgArr,
          });
        }
      })
    };
    wx.request({
      url: app.globalData.url + "getUserCollectionList",
      data: {
        userId: wx.getStorageSync("userId"),
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data =  res.data.data
        console.info(data);
        for (var i = 0; i < data.length;i++){
          var productid = data[i].productId;
          if (productid == that.data.productid) {
            that.setData({
              collection:1
            })
          }
        }
        console.info(that.data.collection);
      },
    })
    var type = 1;
    if (that.data.type == 2) {
      type=2;
    }
    wx.request({
      url: app.globalData.url + "shareProduct",
      method: "GET",
      data: {
        productId: productid,
        userId: wx.getStorageSync("userId"),
        type: type
      },
      success: function (res) {
        var data = res.data;
        if (data.result == 1) {
          that.setData({
            shareImg: data.data.replace("http:", "https:")
          })
        }
      }
    });
  },
  onShow:function(){
    var that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
        } else {
          wx.reLaunch({
            url: '/pages/zcuslist/index?partnerUserId=' + that.data.partnerUserId + '&back=1&productid=' + that.data.productId,
          })
        }
      }
    })
    that.getAddress(that.data.productId);
  },
  onReady: function () {
    var that = this;
   // that.interval();
  },
  //预览图片
  previewImage: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: this.data.imgUrls // 需要预览的图片http链接列表  
    })
  },
  // 收藏
  addLike() {
    this.setData({
      isLike: !this.data.isLike
    });
    
  },
  // 跳到购物车
  toCar() {
    wx.switchTab({
      url: '/pages/shoppingCart/shoppingCart?userId=' + this.data.producData.userId
    })
  },
  // 立即购买\加入购物车
  immeBuy(e) {
    var that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
        } else {
          // 未授权，跳转到授权页面
          wx.reLaunch({
            url: '/pages/zcuslist/index?partnerUserId=' + that.data.partnerUserId,
          })
        }
      }
    })
    if(that.data.productSpec != undefined){
        if(!that.data.twoChoose){
          wx.showToast({
            title: '请选择规格',
            icon:'none'
          })
          return;
        }
        
    }
    
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          console.info(that.data.num);
          console.info(that.data.producData.inventoryQuantity);
          if (that.data.num > that.data.producData.inventoryQuantity) {
            wx.showToast({
              title: "库存不足",
              icon: 'none',
              duration: 2000
            })
            return;
          } else {
            if (that.data.type != 2) {
              if (that.data.producData.seckillLimitNum != 0) {
                if (that.data.num > that.data.producData.seckillLimitNum) {
                  wx.showToast({
                    title: "超过限购数量",
                    icon: 'none',
                    duration: 2000
                  })
                  return;
                }
              }
            }
            if (that.data.type == 2 && that.data.pintuantype == 0) {
              if (that.data.producData.groupShoppingLimitNum != 0) {
                if (that.data.num > that.data.producData.groupShoppingLimitNum) {
                  wx.showToast({
                    title: "超过限购数量",
                    icon: 'none',
                    duration: 2000
                  })
                  return;
                }
              }
            }
            console.info(that.data.num);
            if (that.data.num > that.data.producData.inventoryQuantity){
              wx.showToast({
                title: "库存不足",
                icon: 'none',
                duration: 2000
              })
              return;
            }
            if (that.data.flag == 1) {
              wx.request({
                url: app.globalData.url + "modifyShoppingCart",//给函数传递服务器地址参数 
                data: {
                  productId: that.data.producData.productId,
                  userId: wx.getStorageSync("userId"),
                  num: that.data.num,
                  specPriceId:that.data.priceId
                },//给服务器传递数据，本次请求不需要数据，可以不填
                header: {
                  'content-type': 'application/json' // 默认值，返回的数据设置为json数组格式
                },
                success: function (res) {//打印出返回的数据
                  //that.toCar();
                  // that.toCar();
                  if (res.data.result == 0) {
                    wx.showToast({
                      title: '' + res.data.errmsg,
                      icon: 'none',
                      duration: 2000
                    })
                  } else {
                    wx.showToast({
                      title: '加入购物车成功',
                      icon: 'success',
                      duration: 2000
                    });
                  }
                }
              })

            } else if (that.data.flag == 2) {
              if (that.data.point == undefined) {
                that.setData({
                  point: 0
                })
              }
              var specString = "";
                    for(var i=0;i<that.data.specNameList.length;i++){
                      specString+=that.data.specNameList[i]+"-";
                    }
                    specString = specString.substring(0,specString.length-1)
              if (that.data.typeShow == 2) {
                if(that.data.priceId!=undefined){
                  var plist = '[{"productId":"' + that.data.producData.productId + '","num":' + that.data.num + ',"price":' + that.data.price + ',"title":"' + that.data.producData.title + '","thumbnailImage":"' + that.data.producData.thumbnailImage + '","point":' + that.data.point + ',"inventoryQuantity":' + that.data.producData.inventoryQuantity + ',"groupShoppingLimitNum":' + that.data.producData.groupShoppingLimitNum +',"specPriceId":' +that.data.priceId  +',"specString":"' +specString +'"}]';
                }else{
                  var plist = '[{"productId":"' + that.data.producData.productId + '","num":' + that.data.num + ',"price":' + that.data.price + ',"title":"' + that.data.producData.title + '","thumbnailImage":"' + that.data.producData.thumbnailImage + '","point":' + that.data.point + ',"inventoryQuantity":' + that.data.producData.inventoryQuantity + ',"groupShoppingLimitNum":' + that.data.producData.groupShoppingLimitNum +'}]';//',"specString":' +specString +
                }
               
              } else {
                if(that.data.priceId!=undefined){
                  var plist = '[{"productId":"' + that.data.producData.productId + '","num":' + that.data.num + ',"price":' + that.data.minPrice + ',"title":"' + that.data.producData.title + '","thumbnailImage":"' + that.data.producData.thumbnailImage + '","point":' + that.data.point + ',"seckillNum":' + that.data.producData.seckillLimitNum + ',"inventoryQuantity":' + that.data.producData.inventoryQuantity + ',"specPriceId":' +that.data.priceId  +',"specString":"' +specString +'"}]';
                }else{
                  var plist = '[{"productId":"' + that.data.producData.productId + '","num":' + that.data.num + ',"price":' + that.data.minPrice + ',"title":"' + that.data.producData.title + '","thumbnailImage":"' + that.data.producData.thumbnailImage + '","point":' + that.data.point + ',"seckillNum":' + that.data.producData.seckillLimitNum + ',"inventoryQuantity":' + that.data.producData.inventoryQuantity +'}]';
                }
               
              }
              console.info(plist);
              //此处跳转到修改订单页面
              that.setData({
                pAndNList: plist,
              })
              var addrId= 0;
              if (that.data.addressList[that.data.index]===undefined){
                addrId = 0
              } else {
                addrId = that.data.addressList[that.data.index].addrId
              }
              console.info(that.data.lipinka);
              console.info("这是购买" + that.data.type + '=======' + that.data.buyMethod);
              if (that.data.type==undefined) {
                var type1=1;
              } else {
                var type1= that.data.type
              }
              if (that.data.type == 2 && that.data.buyMethod == 1) {
                if (that.data.typeShow == 2) {//开团价格
                  wx.navigateTo({
                    url: '/pages/confirmOrder/confirmOrder?userId=' + this.data.producData.userId + '&pAndNList=' + that.data.pAndNList + '&addrId=' + addrId + '&index=' + that.data.index + '&type=2&typeShow=' + that.data.typeShow  
                  })
                } else {
                  console.info('dakdjakjdd;ak;adk');
                  wx.navigateTo({
                    url: '/pages/confirmOrder/confirmOrder?userId=' + this.data.producData.userId + '&pAndNList=' + that.data.pAndNList + '&addrId=' + addrId + '&index=' + that.data.index + '&type=1&typeShow=0&yushou=' + e.currentTarget.dataset.yushou + '&consignmenttimestr=' + that.data.bookingConsignmentTime + '&lipinka=' + that.data.lipinka + '&communityGroup=' + that.data.communityGroup + '&nickname=' + that.data.nickname + '&community=' + that.data.community + '&communityheadid=' + that.data.communityheadid+'&type=' + that.data.type
                  })
                }
              } else {
                console.info();
                var type = that.data.type;
                if (that.data.pintuantype == 1) {
                  type = that.data.pintuantype
                }
                wx.navigateTo({
                  url: '/pages/confirmOrder/confirmOrder?userId=' + this.data.producData.userId + '&pAndNList=' + that.data.pAndNList + '&addrId=' + addrId + '&index=' + that.data.index + '&type=1&typeShow=0&yushou=' + e.currentTarget.dataset.yushou + '&consignmenttimestr=' + that.data.bookingConsignmentTime + '&lipinka=' + that.data.lipinka + '&communityGroup=' + that.data.communityGroup + '&nickname=' + that.data.nickname + '&community=' + that.data.community + '&communityheadid=' + that.data.communityheadid + '&type=' + type
                })
              }
            }
            that.modal_none();
          }
        } else {
          // 未授权，跳转到授权页面
          if(that.data.type!=2){
            that.setData({
              type:0
            })
          }
          wx.reLaunch({
            url: '/pages/zcuslist/index?productid=' + that.data.productid + '&type=' + that.data.type + '&partnerUserId=' + this.data.partnerUserId,
          })
        }
      }
    })
  },
  // 弹出
  modal_show: function (e) {
    var that = this;
    var flag = e.currentTarget.dataset.flag;
    var type1 = e.currentTarget.dataset.type;
    var buyMethod = e.currentTarget.dataset.buymethod;
    that.setData({
      buyMethod: buyMethod
    });
    if (buyMethod == 0) {
      that.setData({
        pintuantype: 1
      })
    } else {
      that.setData({
        pintuantype: 0
      })
    }
    that.setData({
      flag: flag,
      choose_modal: "block",
      typeShow: type1
    });
  },
  //消失
  modal_none: function () {
    this.setData({
      choose_modal: "none",
      choose1_modal: "none",
      choose2_modal: "none",
      choose3_modal: "none",
      num:1,
    });
    // if(that.data.inventoryQuantity ){

    // }
  },
  toAddress: function () {
    wx.navigateTo({
      url: '/pages/address/address',
    })
  },

  // 弹出
  modal_s: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choo_modal: "block",
    });
  },

  // 弹出
  modal_s1: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choose1_modal: "block",
    });
  },
  // 弹出
  modal_s2: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choose2_modal: "block",
    });
  },
  // 弹出
  modal_s3: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choose3_modal: "block",
    });
  },
  //消失
  modal_n: function () {
    this.setData({
      choo_modal: "none",
      num: 1,
    });
  },
  // 优惠信息
  modal_activity: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choo_modal_activity: "block",
    });
  },
  //优惠信息
  modal_activity_none: function () {
    this.setData({
      choo_modal_activity: "none",
      num: 1,
    });
  },

  // 弹出
  quest_s: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      quest_modal: "block",
    });
  },
  //消失
  quest_n: function () {
    this.setData({
      quest_modal: "none",
      num: 1,
    });
  },

  /* 点击减号 */
  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <=
      1 ? 'disabled' :
      'normal';
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  //加号
  bindPlus: function (e) {
    var that = this;
    var num = that.data.num;
    // 不作过多考虑自增1
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <
      1 ? 'disabled' :
      'normal';
    // 将数值与状态写回
    console.info(that.data.producData.seckillLimitNum);
    if (that.data.type!=2) {
      if (that.data.producData.seckillLimitNum > 0) {
        if (num > that.data.producData.seckillLimitNum) {
          num++;
          wx.showToast({
            title: '超过限购数量',
            icon: "none"
          })
          return;
        }
      }
    }
    if (that.data.type == 2 && that.data.pintuantype == 0) {
      if (that.data.producData.groupShoppingLimitNum > 0) {
        num++;
        if (num > that.data.producData.groupShoppingLimitNum) {
          wx.showToast({
            title: '超过限购数量',
            icon: "none"
          })
          return;
        }
      }
    }

    if (num > that.data.producData.inventoryQuantity) {
      num++;
      wx.showToast({
        title: "库存不足",
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if(that.data.inventoryQuantity > 0){
      if(num > that.data.inventoryQuantity){
        num++;
        wx.showToast({
          title: "该规格商品库存不足",
          icon: 'none',
          duration: 2000
        })
        return;
      }
    }
    
    that.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
   /**
   * 页面分享
   */
  onShareAppMessage: function () {
    var that = this;
      return {
        title: '极味生鲜',
        desc: '分享页面的内容',
        imageUrl: that.data.thumbnailImage,
        path: '/pages/productDetail/productDetail?productid=' + that.data.productid + "&type=" + that.data.type +"&partnerUserId=" + wx.getStorageSync("userId") + '&back=1', // 路径，传递参数到指定页面
      }
  },
  /**
   * 页面朋友圈
   */
  onShareTimeline: function(res) {
  	var that = this;
  	  return {
  	    title: '极味生鲜',
  	    desc: '分享页面的内容',
  	    imageUrl: that.data.thumbnailImage,
  	    path: '/pages/productDetail/productDetail?productid=' + that.data.productid + "&type=" + that.data.type +"&partnerUserId=" + wx.getStorageSync("userId") + '&back=1', // 路径，传递参数到指定页面
  	  }
  },
  bindManual: function (e) {
    var that = this;
    if (that.data.type != 2) {
      if (that.data.producData.seckillLimitNum > 0) {
        if (e.detail.value > that.data.producData.seckillLimitNum) {
          wx.showToast({
            title: '超过限购数量',
            icon: "none"
          })
          that.setData({
            num: e.detail.value
          })
          return;
        }
      } else if (e.detail.value > that.data.producData.inventoryQuantity) {
        wx.showToast({
          title: "库存不足",
          icon: 'none',
          duration: 2000
        })
        that.setData({
          num: e.detail.value
        })
        return;
      } else {
        that.setData({
          num: e.detail.value
        })
      }
    }
    if(that.data.inventoryQuantity > 0){
      if(e.detail.value > that.data.inventoryQuantity){
        wx.showToast({
          title: "该规格商品库存不足",
          icon: 'none',
          duration: 2000
        })
        that.setData({
          num: that.data.inventoryQuantity
        })
        return;
      }else{
        that.setData({
          num: e.detail.value
        })
      }
    }
  },

  navBack: function () {
    var that = this;
    if (that.data.back==1) {
      // wx.redirectTo({
      //   url: '/pages/mallPage/mallPage',
      // })
      wx.switchTab({
        url: '/pages/mallPage/mallPage',
      })
    } else {
      if (that.data.typeName1 != undefined) {
        wx.setStorageSync("typeName1", that.data.typeName1);
      }
      wx.navigateBack({

      })
    }
    
  },

  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.seckillEndTime.replace(/\.|\-/g, '/'));//设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差                              
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        countdown: d + "天" + h + "时" + m + "分" + s +"秒" ,
        d: d,
        h:h,
        m:m,
        s:s
      })
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 100);
    } else {
      console.log('已截止')
      that.setData({
        countdown: '00:00:00'
      })
    }

  },
  //l领取优惠券
  led: function (e) {
    var that = this;
    var productTypeId = e.target.dataset.producttypeid;
    var productId = e.target.dataset.productid;
    wx.request({
      url: app.globalData.url + 'userReceiveCoupon',
      method: 'GET',
      data: {
        userId: wx.getStorageSync("userId"),
        couponId: e.target.dataset.couponid
      },
      success: function (res) {
        if(res.data.result == 0){
          wx.showToast({
            title: ""+res.data.errmsg,
            icon: 'none',
            duration: 1500
          })
        }
        wx.request({
          url: app.globalData.url + "getCouponListBy",
          data: {
            productId: productId,
            productTypeId: productTypeId,
            userId: wx.getStorageSync("userId"),
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            that.setData({
              cpdata: res.data.data
            })
            if (res.data.data.length > 1) {
              console.info(111);
              that.setData({
                cpdatathreshold: res.data.data[0].threshold,
                cpdataprice: res.data.data[0].price
              })
            }
            if (res.data.data.length > 2) {
              that.setData({
                cpdatathreshold1: res.data.data[1].threshold,
                cpdataprice1: res.data.data[1].price,
              })
            }
          },
        })
      },
    });
  },
  toDetail:function(e){
    wx.navigateTo({
      url: '/pages/taskDetail/taskDetail?questionnaireid=' + e.currentTarget.dataset.questionnaireid + "&detailtype=2" 
    })
  },
  lookAllEvaluation: function () {//跳转评价页面
    wx.navigateTo({
      url: '/pages/evaluation/evaluation?productid=' + this.data.producData.productId
    })
  },
  specifications: function (e){
    console.log(e.currentTarget.dataset.val)
      this.setData({
        specifications:e.currentTarget.dataset.type,
        parameter: e.currentTarget.dataset.value
      })
  },
  getAddress: function (productId){
    var that = this;
    console.log(that.data.producData)
    wx.request({
      url: app.globalData.url + "getUserAddressList",
      data: {
        userId: wx.getStorageSync("userId"),
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({
          addressList:res.data.data
        })
        for(var i=0;i<res.data.data.length;i++){
            if(res.data.data[i].defaultAddress){
                that.setData({
                  index:i
                })
            }
        }
        
        wx.request({
          url: app.globalData.url + "getTotalFreight",
          method: "GET",
          data: {
            json: "{'addressId':" + res.data.data[that.data.index].addrId + ",'product':[{'productId':" + that.data.productid + ",'num':1}]}",
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            var data = res.data.data;
            if (res.data.result == 1) {
                if (that.data.reducePrice==0) {
                  that.setData({
                    freight: parseFloat(data.toFixed(2)),
                  })
              }
              that.setData({
                thisFreight:'',
              })
            }else{
              var addrId = that.data.addressList[that.data.index].addrId
                  if (addrId==undefined) {
                    addrId=0;
                  }
              if(addrId != 0){
                that.setData({
                  thisFreight:'不在区域',
                })
              }
            }
          }
        });


      },
    })

  },
  chooseAddr: function (e) {
    var that = this;


    wx.request({
      url: app.globalData.url + "getTotalFreight",
      method: "GET",
      data: {
        json: "{'addressId':" + that.data.addressList[e.currentTarget.dataset.index].addrId + ",'product':[{'productId':" + that.data.productid + ",'num':1}]}",
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data.data;
        if (res.data.result == 1) {
              that.setData({
                freight: parseFloat(data.toFixed(2)),
                index:e.currentTarget.dataset.index
              })
              that.setData({
                thisFreight:'',
              })
        }else{
          var addrId = that.data.addressList[e.currentTarget.dataset.index].addrId
                  if (addrId==undefined) {
                    addrId=0;
                  }
          if(addrId != 0){
            
          }
         
          that.setData({
            thisFreight:'不在区域',
            index:e.currentTarget.dataset.index
          })
        }
      }
    });

    that.setData({
      choose_modal: "none",
      choose1_modal: "none",
      choose2_modal: "none",
      num: 1,
    });
  },
  collectProduct:function(e){
    var that = this;
    wx.request({
      url: app.globalData.url + "userCollectProduct",
      data: {
        productId: that.data.productId,
        userId: wx.getStorageSync("userId"),
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.result==1){
          wx.showToast({
            title: '收藏成功！',
            icon: "none"
          })
          that.setData({
            collection: 1
          })
        }else{
          wx.request({
            url: app.globalData.url + "userCancelCollectionProduct",
            data: {
              productId: that.data.productId,
              userId: wx.getStorageSync("userId"),
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              if (res.data.result == 1) {
                wx.showToast({
                  title: '取消收藏！',
                  icon: "none"
                })
                that.setData({
                  collection: 0
                })
              }
            },
          })
        }
      },
    })
  },
  goGroup: function (e) {
    var that = this;
    var addrId= 0;
    if (that.data.addressList[that.data.index]===undefined){
      addrId = 0
    } else {
      addrId = that.data.addressList[that.data.index].addrId
    }
    wx.navigateTo({
      url: '/pages/assembleDetail/assembleDetail?orderId=' + e.currentTarget.dataset.orderid + '&share=1&type=2&groupShoppingId=' + e.currentTarget.dataset.hisid+'&addrId='+addrId
    })
  },
  goMore: function () {
    var that = this;
    wx.navigateTo({
      url: '/pages/joinGroup/joinGroup'
    })
  },
  getTimeList: function (endTimeList) {
    var that  = this;
    var daysList=new Array();
    var hoursList = new Array();
    var minutesList = new Array();
    var secondsList = new Array();
    console.info("daojishi==" + endTimeList.length);
    var list=[];
    if (endTimeList.length > 3) {
      for (var i = 0; i < 3; i++) {
        list.push(endTimeList[i]);
      }
    } else {
      for (var i = 0; i < endTimeList.length; i++) {
        list.push(endTimeList[i]);
      }
    }
    console.info(list);
    for (var i = 0; i < list.length; i++){
      var sdfDate = list[i].replace(/\.|\-/g, "/");
      var totalSeconds = new Date(sdfDate) - new Date();
      var days = Math.floor(totalSeconds / (24 * 3600 * 1000));
      var leave1 = totalSeconds % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));
      if (hours < 10) {
        hours = '0' + hours;
      }
      var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));
      if (minutes < 10) {
        minutes = '0' + minutes;
      }
      var leave3 = leave2 % (60 * 1000);
      var seconds = Math.floor(leave3 / 1000);
      if (seconds < 10) {
        seconds = '0' + seconds;
      }
      daysList[i] = days;
      hoursList[i] = hours;
      minutesList[i] = minutes;
      secondsList[i] = seconds;
    }
    that.setData({
      daysList: daysList,
      hoursList: hoursList,
      minutesList: minutesList,
      secondsList: secondsList,
    })
    
  },
  // 计时器
  interval: function () {
    const that = this;
    console.log(that.data.gropuShopList+".......")
    if (that.data.gropuShopList != undefined) {
      let timer = setInterval(function () {  // 设置定时器
        var secondsList = that.data.secondsList;
        var minutesList = that.data.minutesList;
        var hoursList = that.data.hoursList;
        var daysList = that.data.daysList;
       
        for (var i = 0; i < that.data.gropuShopList.length; i++) {
          var seconds = parseInt(secondsList[i]);
          var minutes = parseInt(minutesList[i]);
          var hours = parseInt(hoursList[i]);
          var days = parseInt(daysList[i]);
          console.log(secondsList[i] + "," + minutesList[i] + "," + hoursList[i] + "," + daysList[i]+",,,"+i)
          seconds--;
          if (seconds <= 0) {
            seconds = 60;
            minutes--;
            if (minutes <= 0) {
              minutes = 59;
              hours--;
              if (hours <= 0) {
                hours = 23;
                days--;
              }
              if (days < 0) {
                clearInterval(timer);
                that.onLoad();
              }
            }
            if (minutes < 10) {
              minutesList[i] = '0' + minutes;
              that.setData({
                minutesList: minutesList
              })
            } else {
              minutesList[i] = minutes;
              that.setData({
                minutesList: minutesList
              })
            }
          }
          if (seconds < 10) {
            // 少于10补零
            secondsList[i] = '0' + seconds;
            that.setData({
              secondsList: secondsList
            })
          } else {
            secondsList[i] = seconds;
            that.setData({
              secondsList: secondsList
            })
          }
          daysList[i] = days;
          that.setData({
            daysList: daysList
          })
          hoursList[i] = hours;
          that.setData({
            hoursList: hoursList
          })
        }
      }, 1000)
    }
  },
  //视频封面背景
  videoPlay: function (e) {
    var curIdx = e.currentTarget.dataset.index;
    // 没有播放时播放视频
    if (!this.data.playIndex) {
      this.setData({
        playIndex: curIdx,
        autoplay: true
      })
      var videoContext = wx.createVideoContext('video' + curIdx) //这里对应的视频id
      videoContext.play();
    } else { // 有播放时先将prev暂停，再播放当前点击的current
      var videoContextPrev = wx.createVideoContext('video' + this.data.playIndex)
      if (this.data.playIndex != curIdx) {
        videoContextPrev.pause()
      }
      this.setData({
        playIndex: curIdx,
        autoplay: false
      })
      var videoContextCurrent = wx.createVideoContext('video' + curIdx)
      videoContextCurrent.play()
    }
  },
  test(e) {
    console.log(e);
    var state = e.type;
    var that = this;
    if (state == "play") {
      that.setData({
        autoplay: false,
      })
    }
  },
  test2(e) {
    console.log(e)
    var state = e.type;
    var that = this;
    if (state == "pause") {
      that.setData({
        autoplay: true,
      })
    }
  },
  //将编码后的八进制的emoji表情重新解码成十六进制的表情字符
  entitiesToUtf16:function (str) {
    return str.replace(/&#(\d+);/g, function (match, dec) {
      let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;
      let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;
      return String.fromCharCode(H, L);
    });
  },
  chooseSpec:function(e){
    var that = this;
    var specIdList = that.data.specIdList;
    var specNameList = that.data.specNameList;
    if(specIdList[e.currentTarget.dataset.index] == e.currentTarget.dataset.id){
      specIdList[e.currentTarget.dataset.index] = "";
      specNameList[e.currentTarget.dataset.index] = "";
      that.setData({
        specIdList:specIdList,
        specNameList:specNameList,
        twoChoose:false,
        price:that.data.price1
      })
      return;
    }
    specIdList[e.currentTarget.dataset.index] = e.currentTarget.dataset.id;
    specNameList[e.currentTarget.dataset.index] = e.currentTarget.dataset.name;
    that.setData({
      specIdList:specIdList,
      specNameList:specNameList,
    })
        console.log(specIdList)
         var specIdlistString = "";
          for(var i=0;i<specIdList.length;i++){
            specIdlistString+=specIdList[i]+",";
          }
        specIdlistString = specIdlistString.substring(0,specIdlistString.length-1);
        wx.request({
          url: app.globalData.url + "bySpecGetProudctPrice",
          data: {
            productId: that.data.productId,
            specIdList:specIdlistString,
            userId: wx.getStorageSync("userId")
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            if (res.data.result == 1) {
              if(res.data.data.inventoryQuantity > 0){
                if(that.data.type == 2){
                  that.setData({
                    minPrice:res.data.data.groupShoppingPrice,
                    priceId:res.data.data.priceId,
                    inventoryQuantity:res.data.data.inventoryQuantity,
                  })
                }else{
                  that.setData({
                    minPrice:res.data.data.price,
                    priceId:res.data.data.priceId,
                    inventoryQuantity:res.data.data.inventoryQuantity,
                  })
                }
                that.setData({
                  memberPrice: res.data.data.memberPrice,
                })
              }else{
                wx.showToast({
                  title: '库存不足',
                  icon:"none"
                })
                for(var i=0;i<specIdList.length;i++){
                  specIdList[i] = "";
                  specNameList[i] = "";
                  that.setData({
                    specIdList:specIdList,
                    specNameList:specNameList,
                    twoChoose:false,
                    price:that.data.price1
                  })
                }
              }
              
              
            }
            for(var i=0;i<that.data.specIdList.length;i++){
              if(that.data.specIdList[i] == undefined || that.data.specIdList[i] == ""||that.data.specIdList.length < that.data.productSpec.length){
                  that.setData({
                    twoChoose:false,
                    price:that.data.price1,
                  })
              }else{
                that.setData({
                  twoChoose:true,
                })
                
              }
            }
          },
        })
        // for(var i=0;i<that.data.specIdList.length;i++){
        //   if(that.data.specIdList[i] == undefined || that.data.specIdList[i] == ""||that.data.specIdList.length < that.data.productSpec.length){
        //       that.setData({
        //         twoChoose:false,
        //         price:that.data.price1,
        //       })
        //   }
        // }
  },
  // 邀请模块遮罩层
  chooseShare: function () {
    var that = this;
    that.setData({
      share_modal: 'none',
      choo_friends: 'none',
    })
  },
  // f分享朋友圈
  friends: function () {
    this.setData({
      choo_friends: 'block',
      bottom: true,
      share_modal: 'none'
    })
  },
  friends_hid: function (e) {
    this.setData({
      choo_friends: 'none',
      bottom: false
    })
  },
  // 弹出
  share_s: function (e) {
    if(wx.getStorageSync("userId") == ""){
      // 未授权，跳转到授权页面
      wx.reLaunch({
        url: '/pages/zcuslist/index?partnerUserId=' + this.data.partnerUserId,
      })
    } else {
      var flag = e.currentTarget.dataset.flag;
      this.setData({
        flag: flag,
        share_modal: "block",
        bottom: true
      });
    }
  },
  //消失
  share_n: function () {
    this.setData({
      share_modal: "none",
      num: 1,
      bottom: false
    });
  }, 
  // 弹出
  choo_modal_li_s: function(e) {
    this.setData({
      choo_modal_li: "block",
      modalName1:'Image'
    });
  },
  //消失
  choo_modal_li_n: function () {
    this.setData({
      choo_modal_li: "none",
      modalName1: ''
    });
  },
  toIndex:function(){
    this.choo_modal_li_n();
    wx.reLaunch({
      url: '/pages/zcuslist/index?partnerUserId=' + this.data.partnerUserId,
    })
  },
  downloadFile: function () {
    var that = this;
    wx.downloadFile({
      url: that.data.shareImg,
      success: function (res) {
        if (res.statusCode == 200) {
          var img = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: img,
            success: function () {
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              })
            },
            fail(data) {
              if (data.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || data.errMsg === "saveImageToPhotosAlbum:fail auth deny" || data.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存相册',
                  showCancel: false,
                  success: modalSuccess => {
                    wx.openSetting({
                      success(settingdata) {
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.downloadFile({
                            url: that.data.shareImg,
                            success: function (res) {
                              if (res.statusCode == 200) {
                                var img = res.tempFilePath;
                                wx.saveImageToPhotosAlbum({
                                  filePath: img,
                                  success: function () {
                                    wx.showToast({
                                      title: '保存成功',
                                      icon: 'success'
                                    })
                                  }
                                })
                              }
                            }
                          })
                        } else {
                          wx.showToast({
                            title: '拒绝授权无法保存二维码图片',
                            icon: 'none',
                          })
                        }
                      }
                    })
                  }
                })
              }
            }
          })
        }
      }, fail(err) {
        wx.showToast({
          title: err,
          icon: 'none',
        })
      },
    })
  },
})


